<?php
namespace app\api\service;
use think\Request;
use app\api\model\Market;
use app\api\model\MarketList;
use app\api\model\Dc;
class MarketService {
    public function page($page = 1, $size = 10){
        $data 	= Request::instance()->get();
        $where 	= [];

        empty($data['order']) || $where['order_no'] = ['like','%'.$data['order']];

        $where['alliance_id'] = $data['id'];

        $obj = Market::getFinished()->where($where)
        ->paginate($size, false, ['page' => $page]);

        if ($obj->isEmpty()){
            return [];
        }
        return $obj->toArray();
    }

    public static function makeOrderNo()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return  'LS' . $orderSn;
    }

    // 轮询查订单
    public function polling() {
        $getData = Request::instance()->get();
        $data = Market::getFinished()
        ->where('alliance_id', $getData['alliance_id'])
        ->where('online', 1)
        ->where('status', 0)
        ->select();

        return show(1, 'ok', $data, 200);
    }
    // 知道与删除
    public function change(){
        $param = Request::instance()->param();	//获取参数

        if ($param['status'] == 'change') {
            $obj = Market::get($param['id']);
            $obj->status = 1;
            $obj->save();
            return show(1, 'ok', [], 200);
        }else {
            if( Market::destroy($param['id'], true) ){
                return show(1, '删除成功', [], 200);
            }
        }
    }

    // 检测商品数量 减少商品
    public function checkProduct($products, $id){
        $tempReturn = []; // 更新存放数据
        $return = [
            'status' => 0,
            'name'   => '无'
        ];
        $status = false;
        for ($i = 0; $i< count($products); $i++) {
            $item = Dc::where('alliance_id', $id)
            ->where('finished_id', $products[$i]['id'])
            ->find();

            if ($item->num >= $products[$i]['num']) {
                $tempNum = ($item->num - $products[$i]['num']);
                array_push($tempReturn, [
                    'id' => (int)$item->id,
                    'num' => $tempNum]);
            }else {
                $status = true;
                $return['name'] = $products[$i]['name'];
                break;
            }
        }
        if ($status) {
            $return['status'] = 1;
            return $return;
        }
        $newList = new Dc;
        $newList->isUpdate()->saveAll($tempReturn);
        $return['status'] = 0;
        return $return;
    }
    // 保存
    public function save(){ 
        $param = Request::instance()->param();	//获取参数

        $orderNo = $this->makeOrderNo();

        $price = 0;
        $products = $param['product'];
        if ($param['online'] != 0) {
            $status = $this->checkProduct($products, $param['alliance_id']); 
            if ($status['status'] == 1) {
                return show(0, $status['name'] . '数量不足~' , [], 200); 
            }
        }
        // 计算全部价格
        for ($i = 0; $i< count($products); $i++) {
            $temp = $products[$i]['num'] * $products[$i]['price'];
            $price += $temp;
        }

        // 新增
        $obj = new Market;
        $obj->order_no = $orderNo;
        $obj->alliance_id  = $param['alliance_id'];
        $obj->online  = $param['online'];
        $obj->total_price = $price;
        if ($param['online'] == 1) {
            $obj->status = 0;
        }
        // 流水单
        if(!$obj->save()){
            return show(0, '创建失败', [], 200);
        }
        $orderList = new MarketList;
            
        $tempArray = [];
        try{
            for ($i = 0; $i< count($products); $i++) {
                $inner = [];
                $inner['market_id'] = $obj->id;
                $inner['num'] = $products[$i]['num'];
                $inner['price'] = $products[$i]['price'];
                $inner['finished_id'] = $products[$i]['id'];
                array_push($tempArray, $inner);
            }
        }catch(Exption $e) {
            return show(0, 'error', [], 200);
        }
        // 流水商品
        $orderList->saveAll($tempArray);

        return show(1, '下单成功', [], 200);
    }

    public function delete($id){

    	if( Market::destroy($id, true) ){
            return show(1, '删除成功', [], 200);
        }
        
        return show(0, '删除失败', [], 200);
    }
}